In [1]:
import numpy as np
import tensorflow as tf
In [2]:
n = 10 ** 7
In [3]:
# Implementation using python list
def std(x:list):
x_mean = sum(x)/len(x)
y = sum([(v - x_mean) ** 2 for v in x])/len(x)
return y**0.5
In [4]:
%time std(range(n))
Out[4]:
In [5]:
# Implementation using numpy array function
def std_np(x):
x_mean = np.sum(x)/len(x)
return (((x - x_mean) ** 2).mean())** 0.5
In [6]:
%time std_np(np.arange(n))
Out[6]:
As we can see numpy function much fater than that implemtated on python list. There are a built-in function in numpy to compute the standard deviation. Verify the std computed in all three techniques give same result.
In [7]:
%time np.std(np.arange(int(1e7)))
Out[7]:
In [8]:
%%time
n_input = tf.placeholder(dtype=tf.float64)
x = tf.range(0, n_input)
x_mean = tf.reduce_mean(x)
x_std = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(x, x_mean))))
with tf.Session() as sess:
print(sess.run([x_std], feed_dict={n_input: n}))
In [9]:
np.random.seed(1)
W = np.array([2.3, - 5.7, 8.9]).T
b = 1.2
X = np.random.random((10, 3))
y = np.dot(X, W)
print("W: ", W)
In [10]:
print("y: ", y)
In [11]:
W_estimate = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y)
W_estimate
Out[11]:
In [12]:
np.random.seed(1230)
X = np.random.ranf((5, 3))
X
Out[12]:
In [13]:
n = X.shape[0]
X0 = X - np.mean(X, axis = 0)
(X0.T).dot(X0)/n
Out[13]:
In [14]:
np.cov(X, ddof=0, rowvar=False)
Out[14]:
In [15]:
np.var(X[:, 0])
Out[15]:
In [16]:
np.cov(X[:,0], X[:,1], ddof=0)
Out[16]:
Read about Eigen, SVD, PCA decomposition https://www.cc.gatech.edu/~dellaert/pubs/svd-note.pdf
In [17]:
cx = np.cov(X, rowvar=False)
cx
Out[17]:
In [18]:
e, v = np.linalg.eig(cx)
e, v
Out[18]:
In [19]:
Z = X - X.mean(axis=0)
Z
Out[19]:
In [20]:
Z.mean(axis=0)
Out[20]:
In [21]:
U, D, V = np.linalg.svd(Z)
In [22]:
U
Out[22]:
In [23]:
D
Out[23]:
In [24]:
V
Out[24]:
In [25]:
U.dot(U.T)
Out[25]:
In [26]:
V.dot(V.T)
Out[26]:
In [27]:
U[0].dot(U[1]), U[0].dot(U[2]), U[1].dot(U[2])
Out[27]:
In [28]:
V[0].dot(V[1]), V[0].dot(V[2]), V[1].dot(V[2])
Out[28]:
In [29]:
X_0 = np.zeros_like(X)
In [30]:
np.fill_diagonal(X_0, D)
X_0
Out[30]:
In [31]:
U.dot(X_0).dot(V)
Out[31]:
In [ ]: